package net.virtuemed.jt808.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.hibernate.service.spi.ServiceException;

import java.util.Arrays;


/**
 *  二进制转换
 * @Description  BitValue
 * @Author guoyb
 * @Date   2023/10/17 9:55
 */
@Slf4j
public class BitValue {
    @Getter
    private Integer value;
    /**
     * 位图 从右到左
     */
    private boolean[] bytes = new boolean[32];
    private int[] bytes2 = new int[32];
    /**
     * 二进制位图字符串
     */
    @Getter
    private String bitString;

    public BitValue(Integer value) {
        this.value = value;
        if (value != null) {
            bitString = Integer.toBinaryString(value);
            int start = 0;
            for (int i = bitString.length() - 1; i >= 0; i--) {
                char ch = bitString.charAt(i);
                bytes[start] = ch == '1';
                bytes2[start] = ch == '1' ? 1 : 0;
                start++;
            }
        }
    }

    @Override
    public String toString() {
        return "bytes=" + JSONUtil.toJsonStr(bytes2) + "," + JSONUtil.toJsonStr(this);
    }

    /**
     * 从指定位置读取指定长度的字符
     * @param binaryString
     * @param bit
     * @param len
     * @return
     */
    private byte getValue(String binaryString, int bit, int len) {
        if (StrUtil.isEmpty(binaryString)) return 0;
        int start = binaryString.length() - bit - len;
        if (start < 0) return 0;
        int end = start + len;
        String str = binaryString.substring(start, end);
        log.info("二进制---{}", str);
        return Byte.valueOf(str, 2);
    }

    public boolean isTrue(int bit) {
        return bit < 32 && bytes[bit];
    }

    /**
     * 取出当前位置开始,指定长度的字符(会去掉前面的0)
     *
     * @param bit
     * @param len
     * @return
     */
    protected byte getValue(int bit, int len) {
        return getValue(this.bitString, bit, len);
    }

    /**
     * 取出当前位置的字符
     *
     * @param bit
     * @return
     */
    public boolean getBoolean(int bit) {
        return bytes[bit];
    }


    /**
     * 取出当前位置开始,指定长度的字符
     *
     * @param from 下标从0开始
     * @param to   截至的元素下标
     * @return
     */
    public String getChars(int from, int to) {
        int srtLength = bytes2.length;
        if (from < 0 || to <= 0 || from >= srtLength || to > srtLength) {
            throw new ServiceException("字符串截取出错");
        }
        StringBuilder stringBuffer = new StringBuilder();
        int[] newArray = Arrays.copyOfRange(bytes2, from, to);
        //1、通过for循环方式遍历数组
        for (int i = 0; i < newArray.length; i++) {
            //根据索引号获取数组中的元素
            int val = newArray[i];
            stringBuffer.append(String.valueOf(val));
        }
        return stringBuffer.toString();
    }

}
